

import ac = module("utils/commons/array-collection");
import le = module("utils/commons/Locale");
import ut = module("utils/utils");
import ls = module("main/org/sdmx/model/v2/base/LocalisedString");

/**
	* A collection of localised strings. It extends the AS3 ArrayCollection
	* and simply restrict the items type to LocalisedString.
	* 
	* Xavier Sosnovsky
	* 
	* @see LocalisedString
	*/
export class LocalisedStringsCollection extends ac.ArrayCollection<ls.LocalisedString> {

	/*==============================Fields================================*/
		
	private static ERROR_MSG:string = "Only localised strings are " + 
			"allowed in a collection of localised strings. Got: ";

	/*===========================Constructor==============================*/
		
	constructor(source = null) {
		super(source);
	}
    
    /*==========================Public methods============================*/

    /**
        * @private 
        */
    public addItemAt(item: ls.LocalisedString, index: number): ac.ArrayCollection<ls.LocalisedString> {
		if (!(item instanceof ls.LocalisedString)) {
			throw new Error(LocalisedStringsCollection.ERROR_MSG + 
					ut.Utils.getQualifiedClassName(item) + ".");
		} else {
			return super.addItemAt(item, index);
		}
	}
    
    /**
        * @private 
        */
    public setItemAt(item: ls.LocalisedString, index: number): ac.ArrayCollection<ls.LocalisedString> {
        if (!(item instanceof ls.LocalisedString)) {
			throw new Error(LocalisedStringsCollection.ERROR_MSG + 
                ut.Utils.getQualifiedClassName(item) + ".");
		}
		return super.setItemAt(item, index);
	}
		
	/**
		* Gets the text in the supplied language.
		* 
		* @param language The desired language version
		* 
		* @return The text in the supplied language
		*/ 
	public getDescriptionByLocale(language:string):string {
		var localisedString:ls.LocalisedString = 
			this.findByLocale(new le.Locale(language));
		return (null != localisedString) ? localisedString.getLabel() : null;
	}
		
	/*==========================Private methods===========================*/
		
	private findByLocale(locale:le.Locale):ls.LocalisedString {
        var items = this.getItems();
        for (var i = 0; i < items.length; i++) {
            var l = items[i].getLocale();
            if (l.getLanguage() == locale.getLanguage()) {
                return items[i];
            }
        }
        
        return null;
	}
}